package weixin

import (
	"encoding/json"
	"net/http"

	"github.com/spf13/viper"

	"gpt-api/framework/log"
)

type Weixin struct {
}

type Jscode2SessionParams struct {
	AppID     string `json:"appid"`
	Secret    string `json:"secret"`
	JsCode    string `json:"js_code"`
	GrantType string `json:"grant_type"`
}

var apiUrls = map[string]string{
	"jscode2session": "https://api.weixin.qq.com/sns/jscode2session",
	"getPhoneNumber": "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=",
	"getAccessToken": "https://api.weixin.qq.com/cgi-bin/token",
}

func NewWeixin() *Weixin {
	return &Weixin{}
}

func (w *Weixin) Jscode2session(code string) (map[string]string, error) {
	content := map[string]string{}

	apiUrl := apiUrls["jscode2session"] + "?appid=" + viper.GetString("wxMiniProgram.appid") + "&secret=" + viper.GetString("wxMiniProgram.secret") + "&js_code=" + code + "&grant_type=authorization_code"

	// 请求微信接口
	response, err := http.Get(apiUrl)

	if err != nil {
		return content, err
	}

	defer response.Body.Close()

	err = json.NewDecoder(response.Body).Decode(&content)

	if err != nil {
		return content, err
	}

	log.Info("jscode2session response: ", log.Var("content", content))

	return content, nil
}

func (w *Weixin) GetPhoneNumber(encryptedData, iv, sessionKey string) (map[string]interface{}, error) {
	content := map[string]interface{}{}

	// 请求微信接口
	response, err := http.Get(apiUrls["getPhoneNumber"] + sessionKey + "&encryptedData=" + encryptedData + "&iv=" + iv)

	if err != nil {
		return content, err
	}

	defer response.Body.Close()

	err = json.NewDecoder(response.Body).Decode(&content)

	if err != nil {
		return content, err
	}

	return content, nil
}

func (w *Weixin) GetAccessToken() (map[string]interface{}, error) {
	content := map[string]interface{}{}

	// 请求微信接口
	response, err := http.Get(apiUrls["getAccessToken"] + "?grant_type=client_credential&appid=" + viper.GetString("wxMiniProgram.appid") + "&secret=" + viper.GetString("wxMiniProgram.secret"))

	if err != nil {
		return content, err
	}

	defer response.Body.Close()

	err = json.NewDecoder(response.Body).Decode(&content)

	if err != nil {
		return content, err
	}

	return content, nil
}
